package com.tourscool.springboot.starter.redisson.queue;

import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 我长得帅，不需要注释
 *
 * @author Carlton
 * @date 2018/4/4
 */
@Component
@EnableAsync
public class DelayQueueHandler {
    @Autowired
    private RedissonClient mRedissonClient;

    @Async
    public void handler(DelayQueueJob job) {
        final RBlockingQueue<Object> queue = mRedissonClient.getBlockingQueue(job.config().queueName());
        while (true) {
            final Object poll;
            try {
                if (!mRedissonClient.isShutdown() && !mRedissonClient.isShuttingDown()) {
                    poll = queue.poll(1, TimeUnit.MINUTES);
                    if (poll != null) {
                        job.handler(poll);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
